const service = require("../service/user.service");
// 导入错误常量
const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  NAME_HAS_ALREADY_USED,
} = require("../constants/errtypes");

// 导入md5密码加密处理
const md5password = require('../utils/password-handle')

// 验证用户的中间件
const verifyUser = async (ctx, next) => {
  const { name, password } = ctx.request.body;
  // 先不做错误处理和表单处理 18-->2:30
  // console.log(name,password);

  // 判断是否为空
  if (!name || !password) {
    return ctx.app.emit("error", new Error(NAME_OR_PASSWORD_IS_REQUIRED), ctx);
  }

  // 判断有没有重复name
  const result = await service.getUserByName(name);
  //   console.log(result.length);
  if (result.length) {
    console.log("该用户已经注册过了");
    // err 展示不写了
    return ctx.app.emit("error", new Error(NAME_HAS_ALREADY_USED), ctx);
  }
  await next();
};

const handlePassword = async(ctx,next)=>{
  const {password} = ctx.request.body 
  ctx.request.body.password =  md5password(password)

  await next()
}

module.exports = {
  verifyUser,
  handlePassword
};
